package com.xunfei.noteapp

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.MaterialToolbar
import com.xunfei.noteapp.adapter.NoteAdapter
import com.xunfei.noteapp.data.Note
import com.xunfei.noteapp.room.AppDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

    private lateinit var materialToolbar: MaterialToolbar

    private lateinit var recyclerView: RecyclerView

    private lateinit var adapter: NoteAdapter

    private var itemList = mutableListOf<Note>()

    private var allNotes: MutableList<Note> = mutableListOf()
    private lateinit var noteDatabase: AppDatabase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        materialToolbar = findViewById(R.id.toolbar)
        setSupportActionBar(materialToolbar)

        recyclerView = findViewById(R.id.list)
        recyclerView.layoutManager = LinearLayoutManager(this)

        noteDatabase = AppDatabase.getInstance(this)
//        GlobalScope.launch(Dispatchers.IO) {
//            val newNote = Note(
//                title = "3",
//                content = "4",
//            )
//            noteDatabase.noteDao().addNote(newNote)
//        }

        lifecycleScope.launch(Dispatchers.IO) {
            allNotes = noteDatabase.noteDao().getAllNotes()

            withContext(Dispatchers.Main) {
                adapter.updateAllData(allNotes)
            }
        }



//        testData()
        adapter = NoteAdapter(itemList,
            onItemLongClick = {note,pos->
                ItemLongClick(note,pos)
                true },
            onItemClick = {note-> ItemClick(note)})
        recyclerView.adapter = adapter


    }

    fun ItemLongClick(note:Note,pos:Int){
        adapter.deleteDataById(pos)
    }
    fun ItemClick(note:Note){
        val intent = Intent(this,NoteActivity::class.java)
        intent.putExtra("action","fix")
        intent.putExtra("title",note.title)
        intent.putExtra("content", note.content)
        getResult.launch(intent)
    }

    fun testData(){

        for(i in 1..5)
        {
            var note = Note(
                id = i.toLong(),
                title = "标题 $i",
                content = "这是第 $i 项的详细描述内容",
                timestamp = 1751304907000
            )
            itemList.add(note)
        }

    }

    private val getResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
        if(result.resultCode == RESULT_OK)
        {
            val data = result.data
            val action = data?.getStringExtra("action")
            if(action == "add")
            {
                val title = data?.getStringExtra("title")
                val content = data?.getStringExtra("content")
                var timestamp = data?.getLongExtra("timestamp",0L)

                val newNote = Note(title=title.toString(), timestamp = timestamp!!.toLong(), content = content.toString())
                adapter.addData(newNote)
                GlobalScope.launch(Dispatchers.IO) {
                    noteDatabase.noteDao().addNote(newNote)
                }
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.toolbar_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.ic_add -> {
//                Toast.makeText(this,"add 点击", Toast.LENGTH_LONG).show()
                val intent = Intent(this,NoteActivity::class.java)
                intent.putExtra("action","add")
                getResult.launch(intent)
            }
        }
        return super.onOptionsItemSelected(item)
    }
}